package com.tianji.learning.schedule;

import com.tianji.common.utils.DateUtils;
import com.tianji.learning.entity.po.PointsBoardSeason;
import com.tianji.learning.service.IPointsBoardSeasonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

/**
 * 每个月月末凌晨1点执行添加新的赛季
 */

@Component
@Slf4j
@RequiredArgsConstructor
public class PointsBoardSeasonScheduled {

    private final IPointsBoardSeasonService pointsBoardSeasonService;

    // @Scheduled(cron = "0 0 1 L * ?") // 每个月月末凌晨1点执行
    public void addNewSeason() {
        log.info("每个月月末凌晨1点执行添加新的赛季");
        // 1.先查询这个月的赛季
        LocalDate now = LocalDate.now();
        // 得到赛季id
        PointsBoardSeason pointsBoardSeason = pointsBoardSeasonService.queryPointsSeasonByTime(now);

        if (pointsBoardSeason == null) {
            log.info("每个月月末凌晨1点执行添加新的赛季  任务执行失败，没有找到赛季id");
            return;
        }
        // 获取字符串中的数字
        String seasonIdStr = pointsBoardSeason.getName().replaceAll("[^0-9]", "");

        // 2.赛季+1
        int seasonId = Integer.parseInt(seasonIdStr) + 1;

        PointsBoardSeason boardSeason = new PointsBoardSeason();
        boardSeason.setName("第" + seasonId + "赛季");

        // 先根据名称查询是否存在
        PointsBoardSeason pointsBoardSeasonIsExist = pointsBoardSeasonService.queryPointsSeasonByName(boardSeason.getName());
        if (pointsBoardSeasonIsExist != null) {
            // 表示已经存在了，不需要添加
            return;
        }

        // 获取下一个的开始时间和结束时间
        LocalDate nextStartTime = now.plusMonths(1);

        LocalDate monthBegin = DateUtils.getMonthBegin(nextStartTime);
        LocalDate monthEnd = DateUtils.getMonthEnd(nextStartTime);
        boardSeason.setBeginTime(monthBegin);
        boardSeason.setEndTime(monthEnd);

        // 3、添加新的赛季
        pointsBoardSeasonService.addNewSeason(boardSeason);
    }

    public static void main(String[] args) {
        System.out.println("第12赛季".replaceAll("[^0-9]", ""));
    }

}
